package com.iceflame.zxingane;

import java.io.IOException;
import java.util.Vector;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.iceflame.zxingane.camera.CameraManager;
import com.iceflame.zxingane.decoding.CaptureActivityHandler;
import com.iceflame.zxingane.decoding.InactivityTimer;
import com.iceflame.zxingane.view.ViewfinderView;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CaptureActivity extends Activity implements Callback {

	private ViewfinderView viewfinderView;

	private SurfaceView surfaceView;

	private CaptureActivityHandler handler;

	private Vector<BarcodeFormat> decodeFormats;

	private InactivityTimer inactivityTimer;

	private boolean hasSurface;

	private String characterSet;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Config.PREVIEW_WIDTH = getIntent().getIntExtra("width", 0);
		Config.PREVIEW_HEIGHT = getIntent().getIntExtra("height", 0);
		String titleStr = getIntent().getStringExtra("title");
		//String bottomStr = getIntent().getStringExtra("bottom");
		
		Configuration config = getResources().getConfiguration();
		if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Config.CURRENT_ORIENT = Config.Orient.Landscape;
		} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Config.CURRENT_ORIENT = Config.Orient.Portrait;
		}

		FrameLayout pg = new FrameLayout(this);
		pg.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		setContentView(pg);

		surfaceView = new SurfaceView(this);
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		param.gravity = Gravity.CENTER;
		surfaceView.setLayoutParams(param);
		pg.addView(surfaceView);

		viewfinderView = new ViewfinderView(this);
		viewfinderView.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		viewfinderView.setBackgroundColor(0x00000000);
		pg.addView(viewfinderView);
		
		//抬头
		LinearLayout title = new LinearLayout(this);
		title.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, dp2Px(50)));
		title.setOrientation(LinearLayout.HORIZONTAL);
		title.setBackgroundColor(0x99535353);
		title.setVisibility(titleStr == null ? View.GONE : View.VISIBLE);
		pg.addView(title);
		
		TextView titleText = new TextView(this);
		LinearLayout.LayoutParams ttp = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		ttp.gravity = Gravity.CENTER;
		ttp.setMargins(dp2Px(20), 0, dp2Px(20), 0);
		titleText.setLayoutParams(ttp);
		titleText.setGravity(Gravity.CENTER);
		titleText.setTextColor(0xffffffff);
		titleText.setTextSize(sp2px(10));
		titleText.setText(titleStr == null ? "" : titleStr);
		title.addView(titleText);
		
		//底部
//		LinearLayout bottom = new LinearLayout(this);
//		LinearLayout.LayoutParams bparam = new LinearLayout.LayoutParams(
//				LayoutParams.MATCH_PARENT, dp2Px(50));
//		bparam.gravity = Gravity.BOTTOM;
//		bottom.setLayoutParams(bparam);
//		bottom.setBackgroundColor(0x99535353);
//		bottom.setVisibility(bottomStr == null ? View.GONE : View.VISIBLE);
//		pg.addView(bottom);
//		
//		TextView bottomText = new TextView(this);
//		LinearLayout.LayoutParams btp = new LinearLayout.LayoutParams(
//				LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
//		btp.gravity = Gravity.CENTER;
//		btp.setMargins(dp2Px(20), 0, dp2Px(20), 0);
//		bottomText.setLayoutParams(ttp);
//		bottomText.setGravity(Gravity.CENTER);
//		bottomText.setTextColor(0xffffffff);
//		bottomText.setTextSize(sp2px(10));
//		bottomText.setText(bottomStr == null ? "" : bottomStr);
//		bottom.addView(bottomText);
		
		CameraManager.init(getApplication());
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	public void handleDecode(Result obj, Bitmap barcode) {
		inactivityTimer.onActivity();
		viewfinderView.drawResultBitmap(barcode);
		// 结果显示
		Log.i("ZXING",
				"扫描到二维码:" + obj.getBarcodeFormat().toString() + obj.getText());
		ZXingAne.dispatchEvent(EventType.DECODE, obj.
				getBarcodeFormat().name() + "=%|%=" + obj.getText());
		this.finish();
	}
	
	//转换屏幕尺寸
	//private float density = 0.0f;
	private int dp2Px(float dp){
		final float scale = this.getResources().getDisplayMetrics().density; 
        return (int) (dp * scale + 0.5f);  
//		if(density == 0.0){
//			density = getDensity(this);
//		}
//		return (int) (density * dp);
	}
    public int px2dip(float pxValue) { 
        final float scale = this.getResources().getDisplayMetrics().density; 
        return (int) (pxValue / scale + 0.5f); 
    }
    public int px2sp(float pxValue) { 
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity; 
        return (int) (pxValue / fontScale + 0.5f); 
    } 
    public int sp2px(float spValue) { 
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity; 
        return (int) (spValue * fontScale + 0.5f); 
    }  
//	public static float getDensity(Activity activity) {
//		DisplayMetrics metrics = new DisplayMetrics();
//		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
//		float density = metrics.density;
//		return density;
//	}
}